package cn.chiship.sdk.core.encryption;

import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.util.StringUtil;

import java.security.MessageDigest;

/**
 * Md5Util
 *
 * @author lijian
 */
public class Md5Util {

	private Md5Util() {

	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n += 256;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return HEX_DIGITS[d1] + HEX_DIGITS[d2];
	}

	private static final String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	public static String md5(String origin, String charsetName) {
		try {
			String resultString = origin;
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (StringUtil.isNullOrEmpty(charsetName)) {
				charsetName = BaseConstants.UTF8;
			}
			resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));
			return resultString.toLowerCase();
		}
		catch (Exception e) {
			return "";
		}
	}

	public static String md5(String content) {
		try {
			return md5(content, "UTF-8");
		}
		catch (Exception e) {
			return null;
		}
	}

}
